package models

import (
	"GoServer/common"
	"GoServer/message"
	"GoServer/utils/debug"
	"GoServer/utils/tool"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/spf13/viper"
	"gopkg.in/fatih/set.v0"
)

type Node struct {
	UserId        string          /// 玩家id
	RoomId        string          /// 房间id
	Conn          *websocket.Conn /// 连接
	Addr          string          /// 客户端地址
	FirstTime     uint64          /// 首次连接时间
	HeartbeatTime uint64          /// 心跳时间
	LoginTime     uint64          /// 登录时间
	DataQueue     chan []byte     ///	消息
	GroupSets     set.Interface   ///
	GameName      string          ///游戏名字
}

// 更新用户心跳
func (node *Node) Heartbeat(currentTime uint64) {
	node.HeartbeatTime = currentTime
}

// 用户心跳是否超时
func (node *Node) IsHeartbeatTimeOut(currentTime uint64) (timeout bool) {

	result := node.HeartbeatTime+viper.GetUint64("timeout.HeartbeatMaxTime") <= currentTime
	debug.Logf(debug.Info, fmt.Sprintf("[ws]: [%s], [IsHeartbeatTimeOut]: %t", node.Addr, result))
	if result {
		debug.Logln(debug.Error, "心跳超时。。。自动下线", node)
		debug.Logf(debug.Error, fmt.Sprintf("[ws]: [%s], [Heartbeat]: 心跳超时...自动下线", node.Addr))
		timeout = true
	}
	return
}

// 关闭用户连接
func (node *Node) CloseConnect() {
	node.Conn.Close()

	debug.Logf(debug.Error, fmt.Sprintf("[ws]: [%s], [Heartbeat]: time out, 关闭连接", node.Addr))
}

// 启动任务
func (node *Node) StartLiveTask(roomId string, gameName string) {
	if common.Platform == common.Douyin {
		_, commentErr := node.LiveTask(true, roomId, tool.LiveComment, gameName)
		if commentErr != nil {
			/// 通知客户端登录失败
			node.SendLoginFail(message.SCStartCommentTaskFail)
		}
		_, giftErr := node.LiveTask(true, roomId, tool.LiveGift, gameName)
		if giftErr != nil {
			/// 通知客户端登录失败
			node.SendLoginFail(message.SCStartGiftTaskFail)
		}
		_, likeErr := node.LiveTask(true, roomId, tool.LiveLike, gameName)
		if likeErr != nil {
			/// 通知客户端登录失败
			node.SendLoginFail(message.SCStartLikeTaskFail)
		}
	} else if common.Platform == common.Kuaishou {
		_, commentErr := node.LiveTask(true, roomId, tool.LiveComment, gameName)
		if commentErr != nil {
			/// 通知客户端登录失败
			node.SendLoginFail(message.SCStartCommentTaskFail)
		}
	}
}

// 停止任务
func (node *Node) StopLiveTask(roomId string, gameName string) {
	//node.LiveTask(false, roomId, tool.LiveComment, gameName)
	//node.LiveTask(false, roomId, tool.LiveGift, gameName)
	//node.LiveTask(false, roomId, tool.LiveLike, gameName)
}

func (node *Node) SendLoginFail(failCode uint64) {
	msg := message.Message{MsgType: failCode}
	data, err := msg.MarshalBinary()
	if err == nil {
		debug.Logln(debug.Error, "任务启动失败，返消息回客户端：", string(data))
		node.DataQueue <- data
	}
}

func (node *Node) LiveTask(open bool, roomId, msgType string, gameName string) ([]byte, error) {
	if common.TaskExecutor == nil {
		return nil, fmt.Errorf("未注册 LiveTaskExecutor")
	}

	if open {
		return common.TaskExecutor.StartLiveTask(roomId, msgType, gameName)
	}
	return common.TaskExecutor.StopLiveTask(roomId, msgType, gameName)
}
